import router from '@/router'
import { RouteRecordRaw } from 'vue-router'
import { GetToken } from './common'

import { useStore } from '@/stores/index'
import { _t } from '@/assets/lang'
const whiteList = ['/login', '/404']

router.beforeEach((to, _from, next) => {
    if(to.meta.translate_key || "") {
        document.title = _t(`layout.Router.${to.meta.translate_key}`) || _t("common.Title")
    }else {
        document.title = _t("common.Title")
    }
    let token = GetToken()
    const store = useStore()
    store.init()
    if(token) {
        if (to.path === '/login') {
            next({ path: '/' })
        }else {
            store.initUserinfo().then((Routes: RouteRecordRaw[]) => {
                if(store.ListMenu && store.ListMenu.length > 0) {
                    next()
                } else {
                    store.ListMenu = Routes
                    Routes.forEach(v => {
                        router.addRoute(v)
                    })
                    next({ ...to, replace: true })
                }
            })
        }
    }else {
        if (whiteList.indexOf(to.path) !== -1) {
			next()
		} else {
			next(`/login?redirect=${to.fullPath}`)
		}
    }

})


